package controllers

import javax.inject.Inject

import play.api.mvc._
import dao._
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.format.Formats.doubleFormat

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import models.Tables._

case class ChangePasswordData(account: String, password: String, newPassword: String)

class AdminController @Inject()(submissionDao: SubmissionDao, visitorDao: VisitorDao, passwordDao: PasswordDao,
                                cc: ControllerComponents) extends AbstractController(cc) {

  def toIndex = Action.async {
    submissionDao.selectAll.map { x =>
      Ok(views.html.admin.index(x))
    }
  }

  def toVisitorIndex = Action.async {
    visitorDao.selectAll.map { x =>
      Ok(views.html.admin.visitorIndex(x))
    }
  }

  def loginBefore() = Action { implicit request =>
    Ok(views.html.admin.login())
  }

  def changePasswordBefore() = Action { implicit request =>
    Ok(views.html.admin.changePassword())
  }

  val form = Form(
    mapping(
      "account" -> text,
      "password" -> text,
      "newPassword" -> text
    )(ChangePasswordData.apply)(ChangePasswordData.unapply)
  )

  def changePassword = Action.async { implicit request =>
    val data = form.bindFromRequest().get
    passwordDao.selectPassword.flatMap { x =>
      if (data.account == "admin" && data.password == x) {
        val passwordRow = PasswordRow(1, data.newPassword)
        passwordDao.updatePassword(passwordRow).map { y =>
          Redirect(routes.AdminController.loginBefore()).flashing("info" -> "Change password successfully!").withNewSession
        }
      } else {
        Future.successful(Redirect(routes.AdminController.changePasswordBefore()).flashing("info" -> "Account or password is wrong!"))
      }
    }
  }


  def login(phone: String, password: String) = Action.async { implicit request =>
    passwordDao.selectPassword.map { x =>
      if (phone == "admin" && password == x) {
        Redirect(routes.AdminController.toIndex()).withSession("phone" -> phone)
      } else {
        Redirect(routes.AdminController.loginBefore()).flashing("info" -> "Account or password is wrong!")
      }
    }

  }

  def logout = Action {
    Redirect(routes.AdminController.loginBefore()).flashing("info" -> "You've been logged out!").withNewSession
  }


}
